<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { ElMessage } from 'element-plus'
import { addApi, updateApi, queryByIdApi } from '@/api/shop'
import { category } from '@/api/classmanage'

// 路由相关
const route = useRoute()
const router = useRouter()
const isEdit = ref(route.query.id ? true : false)

// 表单数据
const formData = ref({
  id: null,
  title: null,
  subTitle: null,
  description: null,
  content: null,
  categoryId: null,
  // 商品SKU列表
  skuList: []
})

// 商品分类
const categoryList = ref([])
const cascaderOptions = ref([])

// 转换分类数据为级联选择器所需的格式
const transformCategoryData = (data) => {
  return data.map(item => ({
    value: item.id,
    label: item.name,
    children: item.children && item.children.length > 0 ? transformCategoryData(item.children) : undefined
  }))
}

// 获取商品分类
const getCategoryList = async () => {
  try {
    const result = await category()
    categoryList.value = result
    cascaderOptions.value = transformCategoryData(result)
  } catch (error) {
    ElMessage.error('获取商品分类失败: ' + error.message)
    console.error(error)
  }
}

// 获取商品详情（编辑时）
const getShopDetail = async () => {
  if (!isEdit.value) return

  try {
    const res = await queryByIdApi(route.query.id)
    const data = res.data || res
    formData.value = {
      ...data,
      // 确保skuList存在
      skuList: data.skuList || []
    }
  } catch (error) {
    ElMessage.error('获取商品详情失败: ' + error.message)
    console.error(error)
  }
}

// 添加SKU
const addOne = () => {
  formData.value.skuList.push({
    title: '副标题',
    price: 0.0,
    realPrice: 0.0,

    code: '商品条码',
    productWeight: 500,
    productLength: 10,
    productWidth: 30
  })
}

// 移除SKU
const removeSku = (index) => {
  formData.value.skuList.splice(index, 1)
}

// 保存数据
const saveData = async () => {
  // 简单验证
  if (!formData.value.title) {
    ElMessage.warning('请输入商品名称')
    return
  }

  if (formData.value.skuList.length === 0) {
    ElMessage.warning('请至少添加一个SKU')
    return
  }

  try {
    let res
    if (isEdit.value) {
      res = await updateApi(formData.value)
    } else {
      res = await addApi(formData.value)
    }

    if (res.code) {
      ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
      router.push('/shopmanage')
    } else {
      ElMessage.error(res.msg || (isEdit.value ? '修改失败' : '新增失败'))
    }
  } catch (error) {
    ElMessage.error('操作失败: ' + error.message)
    console.error(error)
  }
}

// 取消操作
const cancel = () => {
  router.push('/shopmanage')
}

// 处理级联选择器值变化
const handleCascaderChange = (value) => {
  // value 是一个数组，包含选中项的所有值 [1, 5, 9]
  // 如果只需要最后一级的ID，可以这样处理
  if (value && value.length > 0) {
    formData.value.categoryId = value[value.length - 1]
  } else {
    formData.value.categoryId = null
  }
}

// 页面加载时初始化
onMounted(() => {
  getCategoryList()
  getShopDetail()
})
</script>

<template>
  <div class="shop-form">
    <h3>{{ isEdit ? '修改商品详情' : '新增商品详情' }}</h3>

    <el-form :model="formData" label-width="auto" style="max-width: 800px;">
      <el-form-item label="商品分类" prop="categoryId" :rules="[{ required: true, message: '请选择商品分类', trigger: 'change' }]">
        <el-cascader
          v-model="formData.categoryId"
          :options="cascaderOptions"
          :props="{ expandTrigger: 'hover' }"
          @change="handleCascaderChange"
          placeholder="请选择商品分类"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="商品名字" prop="title" :rules="[{ required: true, message: '请输入商品名字', trigger: 'blur' }]">
        <el-input v-model="formData.title" />
      </el-form-item>

      <el-form-item label="商品描述" prop="description">
        <el-input v-model="formData.description" type="textarea" rows="3" />
      </el-form-item>

      <el-form-item label="商品详情" prop="content">
        <QuillEditor v-model:content="formData.content" contentType="html" theme="snow"
          style="height: 300px; width: 100%;" class="quill-editor" />
      </el-form-item>

      <el-form-item>
        <el-button type="success" @click="addOne">+ 添加SKU</el-button>
      </el-form-item>

      <!-- SKU列表 -->
      <el-card v-for="(sku, index) in formData.skuList" :key="index" style="margin-bottom: 15px;">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="SKU标题" :rules="[{ required: true, message: '请输入SKU标题', trigger: 'blur' }]">
              <el-input v-model="sku.title" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="销售价" :rules="[{ required: true, message: '请输入销售价', trigger: 'blur' }]">
              <el-input v-model="sku.price" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="原价" :rules="[{ required: true, message: '请输入原价', trigger: 'blur' }]">
              <el-input v-model="sku.realPrice" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="商品条码">
              <el-input v-model="sku.code" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-button type="warning" @click="removeSku(index)" style="margin-top: 24px;">
              - 删除
            </el-button>
          </el-col>
        </el-row>

        <el-row :gutter="20" style="margin-top: 10px;">
          <el-col :span="6">
            <el-form-item label="重量(g)">
              <el-input v-model="sku.productWeight" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="长度(cm)">
              <el-input v-model="sku.productLength" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="宽度(cm)">
              <el-input v-model="sku.productWidth" type="number" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-form-item>
        <el-button type="success" @click="saveData">{{ isEdit ? '修改' : '保存' }}</el-button>
        <el-button @click="cancel" style="margin-left: 10px;">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.shop-form {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

h3 {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}
</style>